package com.mxx.common.model;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * @Author itzgyw
 * @Date 2020-01-10
 * @Time 15:00
 * @Description:
 */
@Data
public class Response<T> implements Serializable {
    /**
     * 响应码
     */
    private Integer code;
    /**
     * 响应信息
     */
    private String msg;
    /**
     * 错误信息
     */
    private ErrorMessage error;
    /**
     * 返回数据
     */
    private T data;


    public Response() {
    }

    public Response(Integer code, String msg) {
        this.msg = msg;
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public boolean onNull() {
        return this.data == null;
    }

    public boolean onSuccess() {
        return 0 == this.code;
    }

    public Response<T> failure(String errorCode, String errorMessage) {
        ErrorMessage message = new ErrorMessage();
        message.setCode(errorCode);
        message.setMessage(errorMessage);
        this.error = message;
        return this;
    }

    public Response<T> flushData(T t) {
        this.data = t;
        return this;
    }

    public static <T> Response<T> ok() {
        Response<T> response = new Response<>();
        response.setCode(0);
        response.setMsg("SUCCESS");
        return response;
    }

    public static <T> Response<T> of(T data) {
        Response<T> response = new Response<>();
        response.setCode(0);
        response.setMsg("SUCCESS");
        response.setData(data);
        return response;
    }

    public static <T> Response<T> of(ResponseCode code) {
        Response<T> response = new Response<>();
        response.setCode(code.getCode());
        response.setMsg(code.getMessage());
        return response;
    }

    @Override
    public String toString() {
        return "{code=" + code + ",message=" + msg + ",error=" + error + ",data=" + data + "}";
    }

    @Data
    @Accessors(chain = true)
    public static class ErrorMessage implements Serializable {
        /**
         * 错误码
         */
        private String code;
        /**
         * 错误信息
         */
        private String message;

        @Override
        public String toString() {
            return "{code=" + code + ",message=" + message + "}";
        }
    }
}
